/******************************************************************************
 * Copyright (C) 2017 Chengdu Dlhd information industry co. LTD.
 * All Rights Reserved.
 * 本软件为成都顶联互动信息产业有限公司开发研制。未经本公司正式书面同意，其他任何个人、团体不得使用、复制、修改或发布本软件.
 *****************************************************************************/
package net.dgg.dggcloud.service.jrcrm.service.cms;

import net.dgg.dggcloud.core.idwork.KeyWorker;
import net.dgg.dggcloud.core.util.DateUtil;
import net.dgg.dggcloud.core.util.StringUtils;
import net.dgg.dggcloud.service.common.base.SessionManager;
import net.dgg.dggcloud.service.common.base.service.BaseService;
import net.dgg.dggcloud.service.common.exception.BizException;
import net.dgg.dggcloud.service.entity.user.User;
import net.dgg.dggcloud.service.jrcrm.constant.CustomerRecordConstant;
import net.dgg.dggcloud.service.jrcrm.dao.cms.MarketingDao;
import net.dgg.dggcloud.service.jrcrm.dao.customer.CustomerDao;
import net.dgg.dggcloud.service.jrcrm.dao.customer.ReturnVisitCustomerDao;
import net.dgg.dggcloud.service.jrcrm.entity.business.Business;
import net.dgg.dggcloud.service.jrcrm.entity.cms.Marketing;
import net.dgg.dggcloud.service.jrcrm.entity.customer.Customer;
import net.dgg.dggcloud.service.jrcrm.entity.customer.ReturnVisitCustomer;
import net.dgg.dggcloud.service.jrcrm.entity.customer.ReturnVisitRecord;
import net.dgg.dggcloud.service.jrcrm.service.business.BusinessService;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 营销活动业务处理层
 * @ClassName: MarketingService
 * @author 钟鑫
 * @Date: 2017年11月22日 18:48:01
 * @Version V1.0
 */
@Service
public class MarketingService extends BaseService {

    @Autowired
    private MarketingDao marketingDao;

    @Autowired
    private KeyWorker keyWorker;

    @Autowired
    private BillNumberRuleService billNumberRuleService ;

    /**
     * 查询列表
     * @param map 参数
     * @return 结果集合
     */
    public List<Map> queryPageByMap(Map map){
        return marketingDao.queryPageByMap(map);
    }

    /**
     * 根据条件统计数据量
     * @param map 参数
     * @return 统计数量
     */
    public Integer countListByMap(Map map){
        return marketingDao.countListByMap(map);
    }

    /**
     * 根据id获取数据
     * @param id 主键id
     * @return 结果对象
     */
    public Marketing getById(Long id){
        return repository.get(Marketing.class,id);
    }

    /**
     * 新增、修改营销活动
     * @param map
     */
    public void saveOrUpdateMarketing(Map map){
        if (null == map.get("name") || StringUtils.isBlank(map.get("name").toString())){
            throw new BizException("活动名称不能为空",BizException.DEFAULT_CODE);
        }
        if (null == map.get("content") || StringUtils.isBlank(map.get("content").toString())){
            throw new BizException("活动内容不能为空",BizException.DEFAULT_CODE);
        }
        // 活动名称
        String name = map.get("name").toString();
        // 活动内容
        String content = map.get("content").toString();

        Marketing marketing =  new Marketing();
        User loginUser = SessionManager.getCurrentUser();
        String marketingStatus = "";
        if (null != map.get("marketingStatus")){
            marketingStatus = map.get("marketingStatus").toString();
        }
        if (null == map.get("id")){
            marketing.setId(keyWorker.nextId());
            marketing.setCreateUser(loginUser);
            marketing.setUpdaterUser(loginUser);
            marketing.setMarketingDate(map.get("marketingDate").toString());
            marketing.setName(name);
            marketing.setContent(content);
            marketingStatus = StringUtils.isBlank(marketingStatus) ? "UN_PUBLISH" : marketingStatus;
            marketing.setMarketingStatus(marketingStatus);
            if ("HAVE_PUBLISHED".equals(marketingStatus)){
                marketing.setPublisherId(loginUser.getId());
                marketing.setPublisherName(loginUser.getName()+loginUser.getLoginName());
                marketing.setPublishDate(new Date());
            }
            String no = billNumberRuleService.updateBillNumberByCode("HD");
            if (StringUtils.isBlank(no)){
                throw new BizException("获取单据号失败，请重试！", BizException.DEFAULT_CODE);
            }
            marketing.setNo(no);
            repository.save(marketing);
        } else {
            Long id = Long.parseLong(map.get("id").toString());
            if ("create".equals(map.get("type"))){
                marketing.setId(id);
                marketing.setCreateUser(loginUser);
                marketing.setUpdaterUser(loginUser);
                marketing.setMarketingDate(map.get("marketingDate").toString());
                marketing.setName(name);
                marketing.setContent(content);
                marketingStatus = StringUtils.isBlank(marketingStatus) ? "UN_PUBLISH" : marketingStatus;
                marketing.setMarketingStatus(marketingStatus);
                if ("HAVE_PUBLISHED".equals(marketingStatus)){
                    marketing.setPublisherId(loginUser.getId());
                    marketing.setPublisherName(loginUser.getName()+loginUser.getLoginName());
                    marketing.setPublishDate(new Date());
                }
                String no = billNumberRuleService.updateBillNumberByCode("HD");
                if (StringUtils.isBlank(no)){
                    throw new BizException("获取单据号失败，请重试！", BizException.DEFAULT_CODE);
                }
                marketing.setNo(no);
                repository.save(marketing);
            } else {
                marketing = repository.get(Marketing.class,id);
                marketing.setUpdaterUser(loginUser);
                marketing.setMarketingDate(map.get("marketingDate").toString());
                marketing.setName(name);
                marketing.setContent(content);
                if (StringUtils.isNotBlank(marketingStatus)){
                    marketing.setMarketingStatus(marketingStatus);
                }
                repository.saveOrUpdate(marketing);
            }

        }
    }

    /**
     * 根据主键id删除数据
     * @param id 主键
     */
    public void deleteById(Long id){
        repository.deleteEntityById(Marketing.class,id);
    }

    /**
     * 根据主键id、状态status 批量修改营销活动状态
     * @param ids 多个主键id用逗号隔开
     * @param marketingStatus 营销活动
     */
    public void updateStatusByMarketingIds(String ids, String marketingStatus){
        if (StringUtils.isBlank(ids)){
            throw new BizException("营销活动不能为空！",BizException.DEFAULT_CODE);
        }
        if (StringUtils.isBlank(marketingStatus)){
            throw new BizException("状态不能为空！",BizException.DEFAULT_CODE);
        }

        Map map = new HashMap();
        map.put("ids",ids);
        map.put("marketingStatus",marketingStatus);
        User loginUser = SessionManager.getCurrentUser();
        Long userId = loginUser.getId();
        String userName = loginUser.getName()+loginUser.getLoginName();
        map.put("updaterId",userId);
        map.put("updaterName",userName);
        map.put("updaterOrgId",loginUser.getOrgId());
        // 如果是已发布需要将发布人id、发布人姓名、发布时间改为当前人、当前时间
        if ("HAVE_PUBLISHED".equals(marketingStatus)){
            map.put("publisherId",userId);
            map.put("publisherName",userName);
            map.put("publishDate",DateUtil.dateToString(new Date(),"yyyy-MM-dd"));
        }

        marketingDao.updateStatusByMarketingIds(map);
    }
    /**
     * 根据多个主键id删除数据
     * @param ids 多个主键用","隔开
     */
    public void deleteByIds(String ids) {
        if (StringUtils.isBlank(ids)){
            throw new BizException("没有指定删除的营销活动，无法操作！",BizException.DEFAULT_CODE);
        }
        marketingDao.deleteByIds(ids);
    }
}
